package com.hmjk.health.user;

import org.json.JSONException;
import org.json.JSONObject;

import com.hmjk.health.HealthApp;
import com.hmjk.health.R;
import com.hmjk.health.background.NetService;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.format.Time;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.NumberKeyListener;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;

public class ChangePasswordActivity  extends Activity implements OnClickListener, OnTouchListener{
	private final String TAG = ChangePasswordActivity.class.getSimpleName();
	private HealthApp mApp = null;
	private Button mButton;
	private EditText mCrtPwd, mNewPwd, mCfPwd;
	private ImageView mCross;

	public ChangePasswordActivity() {
		// TODO Auto-generated constructor stub
	}
	
	private void logd(String info){
		Log.d(TAG,info);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		logd("onCreate");
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mApp = (HealthApp)getApplication();
		
		setContentView(R.layout.change_password_activity);
		ImageButton back = (ImageButton)findViewById(R.id.back);
		back.setOnClickListener(this);
		
		mButton = (Button)findViewById(R.id.commit);
		mButton.setOnClickListener(this);
		
		mCross = (ImageView)findViewById(R.id.cpcross);
		mCross.setVisibility(View.INVISIBLE);
		
		mCrtPwd = (EditText)findViewById(R.id.cpwdedit);
		mCrtPwd.setKeyListener(new NumberKeyListener(){

			@Override
			public int getInputType() {
				return InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD;
			}

			@Override
			protected char[] getAcceptedChars() {
				char[] allow = mApp.getAllowedChars("Password");
				return allow;
			}
			
		});
		mCrtPwd.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				if(mCrtPwd.hasFocus() == false){
					mCross.setVisibility(View.VISIBLE);
					String iPwd = mCrtPwd.getText().toString().trim();
					if(checkCurrentPassword(iPwd)){
						mCross.setImageResource(R.drawable.tick);
					}else{
						mCross.setImageResource(R.drawable.cross);
					}
				}else{
					mCross.setVisibility(View.INVISIBLE);
				}
			}
		});

		mNewPwd = (EditText)findViewById(R.id.npwdedit);
		mNewPwd.setKeyListener(new NumberKeyListener(){

			@Override
			public int getInputType() {
				return InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD;
			}

			@Override
			protected char[] getAcceptedChars() {
				char[] allow = mApp.getAllowedChars("Password");
				return allow;
			}
			
		});
		mCfPwd = (EditText)findViewById(R.id.cfpwdedit);
		mCfPwd.setKeyListener(new NumberKeyListener(){

			@Override
			public int getInputType() {
				return InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD;
			}

			@Override
			protected char[] getAcceptedChars() {
				char[] allow = mApp.getAllowedChars("Password");
				return allow;
			}
			
		});
		
		ImageButton see = (ImageButton)findViewById(R.id.see);
		see.setOnTouchListener(this);

	}
	
	private boolean checkCurrentPassword(String str){
		
		String pwd = mApp.getPassword();
		if(str.equals(pwd)){
			return true;
		}
		return false;
	}
	
	private boolean checkIsEmpty(String str){
		if((str == null) || str.isEmpty() || (str.length() < 6))
			return true;
		return false;
	}
	
	private boolean checkInput(){
		Boolean ret = true;
		int res = R.string.pwd_err;
		String cPwd = mCrtPwd.getText().toString().trim();
		String nPwd = mNewPwd.getText().toString().trim();
		String cfPwd = mCfPwd.getText().toString().trim();
		
		if(checkIsEmpty(cPwd) || checkIsEmpty(nPwd) || checkIsEmpty(cfPwd)){
			res = R.string.pwd_invalid;
			ret = false;
		}else if(checkCurrentPassword(cPwd) == false){
			res = R.string.pwd_err_current;
			ret = false;
		}else if(nPwd.equals(cfPwd) == false){
			res = R.string.pwd_cnf_err;
			ret = false;
		}

		if(ret == false){
			mApp.showAlertDialog(this, res);
		}
		
		return ret;
	}
	
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			switch(msg.what){
			case HealthApp.MSG_NET_RESPONSE:{
				Bundle b = msg.getData();
				String stamp = b.getString("stamp","ooh!No!");
				boolean canceled = b.getBoolean("canceled", false);
				if(stamp.startsWith("CHANGE_PASSWORD")){
					String sjson = b.getString("json");
					if(sjson != null){
						mApp.dismissWaiting();
						try {
							JSONObject json = new JSONObject(sjson);
							int code = json.getInt("code");
							if(code == 200){
								String state = json.getString("state");
								if(state.equals("00")){
									mApp.showAlertDialog(ChangePasswordActivity.this, getResources().getString(R.string.changePwdOk), R.string.ok, new OnClickListener() {
										
										@Override
										public void onClick(View arg0) {
											// TODO Auto-generated method stub
											setResult(RESULT_OK);
											finish();
										}
									});
									// TODO add success
																		
									return;
								}else if(state.equals("01")){
									mApp.showAlertDialog(ChangePasswordActivity.this, R.string.server_noResp);
									return;
								}else if(state.equalsIgnoreCase("1d")){
									mApp.showAlertDialog(ChangePasswordActivity.this, R.string.pwd_err_current);
									return;
								}
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						mApp.showAlertDialog(ChangePasswordActivity.this, R.string.changePwdError);
					}
				}
			}break;
			}
		}
	};
	
	private void reportPassword(){
		mApp.showWaitting(this, null);
		Intent si = new Intent(this, NetService.class);
		si.setAction(NetService.CHANGE_PASSWORD);
		si.putExtra("uid", mApp.getUID());
		si.putExtra("oldpassword", mCrtPwd.getText().toString().trim());
		si.putExtra("newpassword", mNewPwd.getText().toString().trim());
		
		Time t = new Time();
		t.setToNow();
		String stamp = "CHANGE_PASSWORD" + t.toString(); 
		si.putExtra("stamp",stamp);
		mApp.addNetHandler(stamp, mHandler);
		startService(si);
	}
	
	@Override
	public void onClick(View v) {
		
		switch(v.getId()){
			case R.id.back:{
				finish();
			}break;
			case R.id.commit:{
				if(checkInput() == false){
					return;
				}
				reportPassword();
			}break;
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent e) {
		if(v.getId() == R.id.see){
			
			if(e.getAction() == MotionEvent.ACTION_DOWN){
				//see pwd
				int pos = mNewPwd.getSelectionStart();
				mNewPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
				mNewPwd.setSelection(pos);
			}else if((e.getAction() == MotionEvent.ACTION_UP) ||
					(e.getAction() == MotionEvent.ACTION_CANCEL)){
				//hide pwd
				int pos = mNewPwd.getSelectionStart();
				mNewPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
				mNewPwd.setSelection(pos);
			}
		}
		return false;
	}

}
